<template>
  <div class="app-container checked">

    <div class="filter-container">

      <el-date-picker
        v-model="q_z_formDate"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
        type="daterange"
        range-separator="至"
        start-placeholder="到达客户日期"
        end-placeholder="到达客户日期"
        class="filter-item"
        @change="q_z_selectTime"
      />
      <el-input v-model.trim="query.orderNo" clearable placeholder="订单号" style="width: 130px;" class="filter-item" @keyup.enter.native="search" />
      <el-input v-model.trim="query.materialNo" clearable placeholder="产品料号" style="width: 130px;" class="filter-item" @keyup.enter.native="search" />
      <el-input v-model.trim="query.workerOrderNo" clearable placeholder="工单号" style="width: 130px;" class="filter-item" @keyup.enter.native="search" />
      <!--<el-select v-model.trim="query.status" class="filter-item" filterable placeholder="请选择生产状态" clearable>
        <el-option v-for="(item,index) in valList" :key="index" :label="item.txt" :value="item.val" />
      </el-select>-->
      <el-input v-model.trim="query.note" clearable placeholder="备注" style="width: 150px;" class="filter-item" @keyup.enter.native="search" />
      <el-button style="margin-left:20px;" class="filter-item" type="primary" icon="el-icon-search" @click="search">{{ $t('table.search') }}</el-button>

      <!--<el-button @click="showImportOrder=true"  icon="el-icon-upload" type="primary" class="filter-item" style="margin-left: 10px;">{{ $t('scm.importProductionPlan') }}</el-button>-->
      <!--<el-button class="filter-item" style="margin-left: 10px;" type="danger" icon="el-icon-delete" @click="deleteProductionPlan">{{ $t('scm.deleteProductionPlan') }}</el-button>-->
      <!--<el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-finished" @click="split">{{ $t('table.split') }}</el-button>-->
      <!--<el-button   v-loading="downloadLoading" class="filter-item" style="margin-left: 0px;"
       type="primary" icon="el-icon-download" @click="handledownloadtem">
        导出月生产计划Excel
      </el-button>-->
    </div>

    <el-dialog :visible.sync="showImportOrder" width="30%" title="请使用右侧模板上传月计划">
      <div style="display:flex;align-items:flex-start;justify-content:center">
        <el-upload ref="planRef" :before-upload="beforeUpload" class="filter-item" action="" multiple :limit="1" :on-exceed="handleExceed" :http-request="uploadActionUrl">
          <el-button icon="el-icon-upload" type="primary" class="filter-item" style="margin-left: 10px;">{{ $t('scm.importProductionPlan') }}</el-button>
        </el-upload>
        <el-button style="margin-left:20px;" class="filter-item" type="warning" icon="el-icon-download" @click="downloadExcel('VIDAR BB月生产计划导入.xlsx','vbb.xlsx')">
          下载月计划数据导入模板
        </el-button>
      </div>
    </el-dialog>
    <div style="margin:10px 0 3px 0;color:red;"> 注意：下推条件 ——— ERP生产订单: 1、是开工或完工且未挂起， 2、订单已审核 3、入库上限数量大于汇报选单数量  4、订单勾选首检且是严格匹配。</div>
    <el-table v-loading="loading" :data="tableData" style="width: 100%;margin-bottom: 20px;" row-key="id" highlight-current-row border @selection-change="handleSelectionChange">
      <!--<el-table-column type="selection" width="55"  disabled="true" :selectable="selectInit" fixed="left" />-->
      <el-table-column prop="id" label="系统编号" sortable min-width="120" fixed="left" />
      <el-table-column prop="isThrowbill" label="抛单" sortable />
      <el-table-column prop="orderArrivesDate" label="下达日期" sortable min-width="120">
        <template slot-scope="{row}">
          <span>{{ row.orderArrivesDate | parseTime('{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="orderDate" label="下单日期" sortable width="120">
        <template slot-scope="{row}">
          <span>{{ row.orderDate | parseTime('{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" sortable>
        <template slot-scope="{row}">
          <span v-if="row.status==1" style="color:#ff4d4d;font-weight:bold">未开工</span>
          <span v-else-if="row.status==2" style="color:#cccc00;font-weight:bold">已开工</span>
          <span v-else="row.status==3" style="color:#00b33c;font-weight:bold">已完工</span>
        </template>
      </el-table-column>
      <el-table-column prop="orderNo" label="订单号" sortable min-width="120" />
      <el-table-column prop="customer" label="客户" sortable />
      <el-table-column prop="materialNo" label="产品料号" sortable min-width="270" />
      <el-table-column prop="note" label="备注" show-overflow-tooltip min-width="190" />
      <el-table-column prop="productName" label="产品名称" sortable min-width="270" />
      <el-table-column prop="unit" label="单位" sortable />
      <el-table-column prop="orderNum" label="订单数量" sortable min-width="120" />
      <el-table-column prop="versionNo" label="版本" sortable min-width="120" />
      <el-table-column prop="workerOrderNo" label="工单号" sortable min-width="190" />
      <el-table-column label="行号" prop="ftreeEntity_FSeq" sortable min-width="100" />
      <el-table-column label="导入时间" min-width="140" sortable prop="createTime">
        <template slot-scope="{row}">
          <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="到达客户日期" width="140" sortable prop="arriveCusDate">
        <template slot-scope="{row}">
          <span>{{ row.arriveCusDate | parseTime('{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="月计划开工" width="120">
        <template slot-scope="{row}">
          <span>{{ row.planStartwork | parseTime('{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="月计划完工" width="120">
        <template slot-scope="{row}">
          <span>{{ row.planFinisedwork | parseTime('{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="usedNum" label="已拆分数量" sortable min-width="120" />
      <el-table-column prop="" label="待拆分数量" sortable min-width="120">
        <template slot-scope="{ row, $index }">
          <span>{{ row.orderNum -row.usedNum }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="finishedNum" label="已完成数量" sortable min-width="120" />
      <el-table-column prop="" label="未完成数量" sortable min-width="120">
        <template slot-scope="{ row, $index }">
          <span>{{ row.orderNum -row.finishedNum }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('table.actions')" align="center" min-width="190px" fixed="right">
        <template slot-scope="{ row, $index }">
          <el-button v-if="row.ftreeEntity_FEntryId&&row.fstatus==3&&row.status==3" type="primary" size="mini" @click="handleUpdate(row, $index)">
            向ERP推工时
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="query.pageIndex" :limit.sync="query.pageSize" @pagination="getInfo" />
    <el-dialog
      :before-close="Cancel"
      :close-on-click-modal="false"
      title="月计划拆分为周计划"
      :visible.sync="dialogsplit"
      width="60%"
    >
      <el-form ref="splitform" :label-position="right" :rules="rule" label-width="120px" :model="splitdata">
        <el-form-item label="生产指令单编号">
          <el-input v-model="splitdata.orderNo" disabled />
        </el-form-item>
        <el-form-item label="料件">
          <el-input v-model="splitdata.materialNo" disabled />
        </el-form-item>
        <el-form-item label="月计划生产日期">
          <!--<el-date-picker
            v-model="q_z_formDate1"
            disabled
            :picker-options="pickerOptions0"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="daterange"
            range-separator="至"
            start-placeholder="计划开工日期"
            end-placeholder="计划完工日期"
            class="filter-item"
            @change="q_z_selectTime1"
          />-->
          <el-date-picker
            v-model="q_z_formDate1"
            type="datetimerange"
            disabled
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item label="待拆分数量" prop="prodQty">
          <el-input v-model="number" disabled @keyup.native="number1" />
        </el-form-item>
        <el-form-item label="周生产计划" prop="startTime">

          <!--<el-date-picker
              v-model="z_formDate"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptions0"
              type="week"
              format="yyyy 第 WW 周"
              placeholder="选择周"
              @change="cc"
            />-->

          <el-table

            :data="arrweek"
            border
            fit
            highlight-current-row
            style="width: 100%; margin:30px 0;"
          >
            <el-table-column min-width="250px" align="center" label="计划周">
              <template slot-scope="{row,$index}">

                <el-date-picker
                  v-model="row.z_formDate"
                  :disabled="row.disable==2"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :picker-options="pickerOptions0"
                  type="week"
                  format="yyyy 第 WW 周"
                  placeholder="选择周"
                  @change="getweekList"
                />
              </template>
            </el-table-column>

            <el-table-column min-width="250px" align="center" label="周生产数量">
              <template slot-scope="{row,$index}">
                <el-input v-model="row.numweek" :disabled="row.disable==2" placeholder="请输入周生产数量" oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,0})?).*$/g, '$1')" />
              </template>
            </el-table-column>
            <el-table-column align="center" width="240">
              <template slot="header">
                <img src="../../../images/tianjia.png" style="width:25px;" @click="addweek">

              </template>
              <template slot-scope="scope">

                <div style="display:flex;align-items:center;justify-content:center;">
                  <img
                    v-show="scope.row.disable==1&&fullscreenLoading!=scope.$index"
                    src="../../../images/jianhao.png"
                    style="width:25px;margin-right:20px;"
                    @click="deleteRow(scope.$index)"
                  >
                  <el-button
                    v-if="scope.row.disable==1"
                    v-loading.fullscreen.lock="fullscreenLoading!=-1&&fullscreenLoading==scope.$index"
                    :disabled="fullscreenLoading!==-1"
                    type="primary"
                    @click="confirmSplit(scope.$index)"
                  >
                    {{ $t('permission.submit') }}
                  </el-button>
                </div>

              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <div style="text-align: right">
          <el-button type="danger" @click="Cancel">
            {{ $t('permission.cancel') }}
          </el-button>

        </div>
      </el-form>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      title="修改月计划"
      :visible.sync="showmonth"
      width="60%"
      :before-close="handleClose"
    >
      <el-form ref="ruleForm" :label-position="right" :rules="rules" label-width="120px" :model="detaildata">
        <el-form-item label="系统编号">
          <el-input v-model="detaildata.id" disabled />
        </el-form-item>
        <el-form-item label="订单编号">
          <el-input v-model="detaildata.orderNo" disabled />
        </el-form-item>
        <el-form-item label="客户" prop="prodQty">
          <el-input v-model="detaildata.customer" disabled />
        </el-form-item>
        <el-form-item label="产品料号" prop="materialNo">
          <el-input v-model="detaildata.materialNo" disabled />
        </el-form-item>
        <el-form-item label="产品料号" prop="materialNo">
          <el-input v-model="detaildata.materialNo" disabled />
        </el-form-item>
        <el-form-item label="订单数量" prop="orderNum">
          <el-input v-model="detaildata.orderNum" placeholder="订单数量" maxlength="9" @keyup.native="number2" />
        </el-form-item>

        <el-form-item label="计划完工日期" prop="q_z_formDate1">
          <!--<el-date-picker
            v-model="q_z_formDate1"
            :picker-options="pickerOptions0"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="daterange"
            range-separator="至"
            start-placeholder="计划开工日期"
            end-placeholder="计划完工日期"
            class="filter-item"
            @change="q_z_selectTime1"
          />-->
          <el-date-picker
            v-model="q_z_formDate1"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="q_z_selectTime1"
          />
        </el-form-item>
        <el-form-item label="到达客户日期" prop="arriveCusDate">
          <el-date-picker
            v-model="detaildata.arriveCusDate"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="date"
            placeholder="选择日期"
          />

        </el-form-item>
        <div style="text-align: right">
          <el-button type="danger" @click="showmonth=false">
            {{ $t('permission.cancel') }}
          </el-button>
          <el-button type="primary" @click="confirmUpdata">
            {{ $t('permission.confirm') }}
          </el-button>
        </div>
      </el-form>
    </el-dialog>

  </div>
</template>
<script>
import { updateMonth, sureAddMopOrder, addDetail, getInfo, deleteAll, impProductionPlanData, splitList,
  continuityList, splitSbmit, getChaiFenPage, getTurns, monthExpExcel, tuiTime } from '@/api/productionPlan'
import moment from 'moment'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { deepClone, downLoadTemplate } from '@/utils'
export default {
  name: 'Productionplan',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      number: 0,
      filename: '月生产计划.xls',
      showImportOrder: false,
      valList: [{
        txt: '默认全部',
        val: ''
      },
      {
        txt: '未开工',
        val: '1'
      }, {
        txt: '已开工',
        val: '2'
      }, {
        txt: '已完工',
        val: '3'
      }
      ],
      q_z_formDate1: [],
      showmonth: false,
      q_z_formDate: [],

      pickerOptions0: {
        firstDayOfWeek: 1,
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7// 如果没有后面的-8.64e7就是不可以选择今天的
        }
      },
      type: 1,
      orderid: '',
      chooseTurnList: [],
      TurnList: [],
      dialogsplitTwo: false,
      z_formDate: '',
      rules: {
        orderNum: [
          { required: true, message: '请填写订单数量', trigger: 'blur' }
        ],
        arriveCusDate: [
          { required: true, message: '请选择到达客户日期', trigger: 'blur' }
        ],
        q_z_formDate1: [
          { required: true, message: '请选择计划完工日期', trigger: 'blur' }
        ]
      },
      rule: {
        // prodQty: [
        //   { required: true, message: '请填写生产数量', trigger: 'blur' }
        // ],

      },
      splitdata1: [],
      splitdata: {
        standHour: ''
      },
      dialogsplit: false,
      selectedList: [],
      id: 1,
      dialogVisible: false,
      dialogType: 'new',
      total: 0,
      query: {

        FStatus: 3,
        status: '3',
        pageSize: 10,
        pageIndex: 1
      },
      tableData: [],
      detaildata: {},
      checked: [],
      loading: true,
      downloadLoading: false,
      arrweek: [],
      chaifentype: 1,
      chaifentype1: 1,
      fullscreenLoading: -1
    }
  },
  created() {

  },
  mounted() {
    this.getInfo()
  },
  methods: {
    beforeUpload(file) {
      const size10M = file.size / 1024 / 1024 <= 2
      if (!size10M) {
        this.$message.warning('上传文件大小不能超过 2MB!')
        return false
      }
    },
    Cancel() {
      this.getInfo()
      this.dialogsplit = false
    },

    getweekList() {
      console.log(this.arrweek)
    },
    deleteRow(index) {
      this.arrweek.splice(index, 1)
    },
    addweek() {
      this.arrweek.push({
        z_formDate: '',
        numweek: '',
        startTime: '',
        endTime: '',
        disable: 1
      })
    },
    handledownloadtem() {
      this.downloadLoading = true
      const obj = deepClone(this.query)
      delete obj.pageIndex
      delete obj.pageSize
      monthExpExcel(obj).then(res => {
        const content = res
        const blob = new Blob([content]) // 构造一个blob对象来处理数据
        const fileName = this.filename // 导出文件名
        if ('download' in document.createElement('a')) { // 支持a标签download的浏览器
          const link = document.createElement('a') // 创建a标签
          link.download = fileName // a标签添加属性
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          document.body.appendChild(link)
          link.click() // 执行下载
          URL.revokeObjectURL(link.href) // 释放url
          document.body.removeChild(link) // 释放标签
        } else { // 其他浏览器
          navigator.msSaveBlob(blob, fileName)
        }
        setTimeOut(() => {
          this.downloadLoading = false
        })
      }).catch(() => {
        this.downloadLoading = false
      })
    },
    downloadExcel(nameOrigin, name) {
      downLoadTemplate(nameOrigin, name)
    },
    z_selectTime(value1) {
      console.log(value1)
      // this.splitdata.startTime = value1[0]
      // this.splitdata.endTime = value1[1]
      // let aaa= this.getIntervalHour( new Date(value1[0]),new Date(value1[1]))
      // this.$set(this.splitdata,"standHour",aaa)
    },
    getNowFormatDate() {
      const date = new Date()
      const seperator1 = '-' // 格式分隔符
      const year = date.getFullYear() // 获取完整的年份(4位)
      let month = date.getMonth() + 1 // 获取当前月份(0-11,0代表1月)
      let strDate = date.getDate() // 获取当前日(1-31)
      if (month >= 1 && month <= 9) month = '0' + month // 如果月份是个位数，在前面补0
      if (strDate >= 0 && strDate <= 9) strDate = '0' + strDate // 如果日是个位数，在前面补0

      const currentdate = year + seperator1 + month + seperator1 + strDate + ' ' + '00:00:00'
      return currentdate
    },
    ccChange(value1, index) {
      // moment().subtract(1, 'day').format('YYYY-MM-DD')
      console.log(value1)
      if (value1) {
        const weekOfday = moment(value1).format('E')
        const Monday = moment(value1)
          .subtract(weekOfday - 1, 'days')
          .format('YYYY-MM-DD HH:mm:ss') // 周一日期
        const Sunday = moment(value1)
          .add(7 - weekOfday, 'days')
          .format('YYYY-MM-DD HH:mm:ss') // 周日日期
        console.log(Monday)
        //  this.query.startTime=value1
        this.arrweek[index].startTime = Monday
        this.arrweek[index].endTime = Sunday

        if (new Date(this.arrweek[index].startTime) - 0 + 86400000 * 1 < new Date().getTime()) {
          console.log(weekOfday)
          const bbb = new Date().getTime()
          console.log(bbb)
          const aaa = this.getNowFormatDate()
          console.log(aaa)
          this.arrweek[index].startTime = aaa
        }

        console.log(this.splitdata)
      } else {
        this.arrweek[index].startTime = ''
        this.arrweek[index].endTime = ''
      }
    },
    cc(value1) {
      // moment().subtract(1, 'day').format('YYYY-MM-DD')
      console.log(value1)
      if (value1) {
        const weekOfday = moment(value1).format('E')
        const Monday = moment(value1)
          .subtract(weekOfday - 1, 'days')
          .format('YYYY-MM-DD HH:mm:ss') // 周一日期
        const Sunday = moment(value1)
          .add(7 - weekOfday, 'days')
          .format('YYYY-MM-DD HH:mm:ss') // 周日日期
        console.log(Monday)
        //  this.query.startTime=value1
        this.splitdata.startTime = Monday
        this.splitdata.endTime = Sunday

        if (new Date(this.splitdata.startTime) - 0 + 86400000 * 1 < new Date().getTime()) {
          console.log(weekOfday)
          const bbb = new Date().getTime()
          console.log(bbb)
          const aaa = this.getNowFormatDate()
          console.log(aaa)
          this.splitdata.startTime = aaa
        }

        console.log(this.splitdata)
      } else {
        this.splitdata.startTime = ''
        this.splitdata.endTime = ''
      }
    },
    newDate(time) {
      var date = new Date(time)
      var y = date.getFullYear()
      var m = date.getMonth() + 1
      m = m < 10 ? '0' + m : m
      var d = date.getDate()
      d = d < 10 ? '0' + d : d
      var h = date.getHours()
      h = h < 10 ? '0' + h : h
      var minute = date.getMinutes()
      minute = minute < 10 ? '0' + minute : minute
      var s = date.getSeconds()
      s = s < 10 ? '0' + s : s
      return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + s
    },

    confirmUpdata() {
      this.detaildata.planStartwork = this.newDate(this.detaildata.planStartwork)
      if ((this.detaildata.planFinisedwork + '') == 'null') {

      } else {
        this.detaildata.planFinisedwork = this.newDate(this.detaildata.planFinisedwork)
      }

      // this.detaildata.planStartwork=this.detaildata.q_z_formDate1[0]
      // this.detaildata.planFinisedwork=this.detaildata.q_z_formDate1[1]
      console.log(this.detaildata)
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          updateMonth(this.detaildata).then(res => {
            if (res.isSuccess) {
              this.showmonth = false
              this.getInfo()
              this.$notify({

                dangerouslyUseHTMLString: true,
                message: '修改成功',
                type: 'success'
              })
            } else {
              this.$notify({
                title: 'error',
                dangerouslyUseHTMLString: true,
                message: `
                        <div> ${res.message}</div>
                      `,
                type: 'error'
              })
            }
          })
        } else {
          return false
        }
      })
    },
    handleUpdate(row) {
      this.$confirm('向erp推工时，确认提交？', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        tuiTime(row.id).then((res) => {
          console.log(res)
          if (res.isSuccess) {
            console.log(322332)
            this.$message({
              type: 'success',
              message: '提交成功!'
            })

            this.getInfo()
          } else {
            console.log(1332)
            console.log(res.message)
            this.$message({
              type: 'error',
              message: res.message
            })
          }
        })
      }).catch(err => {

      })
    },
    q_z_selectTime1(value1) {
      console.log(value1)

      if (value1) {
        this.detaildata.planStartwork = value1[0]
        this.detaildata.planFinisedwork = value1[1]
      } else {
        this.detaildata.planStartwork = ''
        this.detaildata.planFinisedwork = ''
      }
      console.log(this.detaildata)
    },

    q_z_selectTime(value1) {
      if (value1) {
        this.query.startTime = value1[0]
        this.query.endTime = value1[1]
      } else {
        this.query.startTime = ''
        this.query.endTime = ''
      }
    },

    number1() {
      this.splitdata.prodQty = this.splitdata.prodQty.replace(/[^\.\d]/g, '')
      this.splitdata.prodQty = this.splitdata.prodQty.replace('.', '')
    },
    number2() {
      this.detaildata.orderNum = this.detaildata.orderNum.replace(/[^\.\d]/g, '')
      this.detaildata.orderNum = this.detaildata.orderNum.replace('.', '')
    },
    confirmWorkProcedure() {
      if (this.chooseTurnList.length == 0) {
        this.$message.warning(`请选择生产工序！`)
        return false
      }
      this.chooseTurnList = this.chooseTurnList.toString()
      const obj = {
        orderId: this.orderid,
        turnIds: this.chooseTurnList
      }
      addDetail(obj).then((res) => {
        this.$message({
          type: 'success',
          message: '提交成功!'
        })
        this.dialogsplitTwo = false
        this.getInfo()
      })
      console.log(this.splitdata)
      const obj1 = this.splitdata
      obj1.id = this.orderid
      console.log(obj1)
      sureAddMopOrder(obj1).then((res) => {
        //  this.$message({
        //   type: 'success',
        //   message: '提交成功!'
        // })
        //  this.dialogsplitTwo=false;
        //  this.getInfo()
      })
    },
    selectInit(row, index) {
      if (row.usedNum >= row.orderNum) {
        return false
      } else {
        return true
      }
    },
    checkData() {
      console.log(this.arrweek)
      const beginTime = this.arrweek.map(value => value.z_formDate)
      console.log(beginTime)
      const beginTimeSet = new Set(beginTime)
      console.log(beginTimeSet)
      console.log(beginTimeSet.size)
      console.log(beginTime.length)
      if (beginTimeSet.size != beginTime.length) {
        // this.$message({

        //   message: '任务中时间有重复!',

        //   type: 'warning'

        // });
        console.log(233232)
        return false
      } else {
        return true
        console.log(444)
      }
      // for (var i=0; i<this.arrweek.length; i++) {
      //     for (var j=i+1; j<this.arrweek.length; j++) {
      //         if (this.arrweek[i].z_formDate == this.arrweek[j].z_formDate) {

    //             return false;
    //         }
    //     }
    // }
    },

    confirmSplit(index) {
      this.chaifentype = 1
      this.chaifentype1 = 1
      this.splitdata.planId = this.selectedList
      const numcount = 0
      if (!this.arrweek[index].z_formDate) {
        this.$message({
          type: 'warning',
          message: '请选择周计划日期'
        })
        return false
      }
      if (!this.arrweek[index].numweek) {
        this.$message({
          type: 'warning',
          message: '请填写周计划生产数量'
        })
        return false
      }
      if (this.arrweek[index].numweek == 0) {
        this.$message({
          type: 'warning',
          message: '周计划生产数量不能为0'
        })
        return false
      }

      this.ccChange(this.arrweek[index].z_formDate, index)

      if (this.splitdata.prodQty < this.arrweek[index].numweek) {
        this.$message({
          type: 'error',
          message: '周计生产数量不能超过月计划数量,请检查！'
        })
        return false
      }

      if (new Date(this.q_z_formDate1[0]) > new Date(this.arrweek[index].startTime) || new Date(this.q_z_formDate1[1]) < new Date(this.arrweek[index].endTime)) {
        this.chaifentype1 = 4
        this.$confirm('周计划生产日期不在月计划生产日期范围内，提交后将会生成周计划，确认提交？', '警告', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          this.chaifentype = 2
          this.cahifen(index)
          return false
        }).catch(err => {
          this.chaifentype = 3
        })
      }

      if (this.chaifentype == 2 || this.chaifentype1 !== 4) {
        console.log('ppp')
        this.$confirm('提交后将会生成周计划，确认提交？', '警告', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          this.cahifen(index)
        }).catch(err => {

        })
      }
    },
    cahifen(index) {
      // for(var i=0;i<this.arrweek.length;i++){
      //  console.log(this.arrweek[i])
      this.splitdata.startTime = this.arrweek[index].startTime
      this.splitdata.endTime = this.arrweek[index].endTime
      this.splitdata.prodQty = this.arrweek[index].numweek
      this.chaifenTwo(index)
      // }
    },
    getTurnsShow(id, productId) {
      const obj = {
        id: id,
        productId: productId
      }
      this.chooseTurnList = []
      getTurns(obj).then((res) => {
        console.log(res)
        this.dialogsplit = false
        this.TurnList = res.data
        this.splitdata1 = res
        this.dialogsplitTwo = true
      })
    },
    getIntervalHour(startDate, endDate) {
      console.log(startDate, endDate)
      var ms = endDate.getTime() - startDate.getTime()
      if (ms < 0) return 0
      return (ms / 1000 / 60 / 60).toFixed(1)
    },

    handleturn(e) {
      this.chooseTurnList = []
      e.forEach((item) => {
        this.chooseTurnList.push(item.id)
      })
    },
    handleSelectionChange(e) {
      console.log(e)
      this.selectedList = []
      this.checked = e
      e.forEach((item) => {
        this.selectedList.push(item.id)
      })
    },
    split() {
      this.chaifentype = 1
      this.chaifentype1 = 1
      this.orderid = ''
      if (typeof this.selectedList === 'string') {
        this.selectedList = this.selectedList.split(',')
      }
      if (this.selectedList.length !== 1) {
        this.$message.warning(`请勾选1个要拆分的项`)
        return false
      }
      this.arrweek = []
      this.addweek()
      this.q_z_formDate1 = []

      if ((this.checked[0].planFinisedwork + '') == 'null') {
        this.q_z_formDate1 = [this.checked[0].planStartwork, '']
      } else {
        this.q_z_formDate1 = [this.checked[0].planStartwork, this.checked[0].planFinisedwork]
      }

      this.selectedList = this.selectedList.toString()
      splitList(this.selectedList).then((res) => {
        if (res.isSuccess) {
          this.type = 1
          console.log(this.query, this.query.endTime)
          this.splitdata = res.data

          this.splitdata.endTime = this.query.endTime
          this.splitdata.startTime = this.query.startTime
          console.log(this.splitdata)
          this.number = this.splitdata.prodQty
          this.z_formDate = ''
          this.dialogsplit = true
        } else {
          this.$message.error(res.message)
        }
      })
    },
    splitTwo(index) {
      this.orderid = ''
      if (typeof this.selectedList === 'string') {
        this.selectedList = this.selectedList.split(',')
      }
      if (this.selectedList.length !== 1) {
        this.$message.warning(`请勾选1个要拆分的项`)
        return false
      }
      //  this.arrweek=[]

      this.q_z_formDate1 = []

      if ((this.checked[0].planFinisedwork + '') == 'null') {
        this.q_z_formDate1 = [this.checked[0].planStartwork, '']
      } else {
        this.q_z_formDate1 = [this.checked[0].planStartwork, this.checked[0].planFinisedwork]
      }

      this.selectedList = this.selectedList.toString()
      splitList(this.selectedList).then((res) => {
        if (res.isSuccess) {
          this.type = 1
          console.log(this.query, this.query.endTime)
          this.splitdata = res.data

          this.splitdata.endTime = this.query.endTime
          this.splitdata.startTime = this.query.startTime
          console.log(this.splitdata)
          this.number = this.splitdata.prodQty
          if (this.number == 0) {
            this.getInfo()
            this.dialogsplit = false
          }
          this.z_formDate = ''
          // this.chaifenTwo(index)
        } else {
          this.$message.error(res.message)
        }
      })
    },
    chaifenTwo(i) {
      const obj = deepClone(this.splitdata)
      obj.startTime = this.arrweek[i].startTime
      obj.endTime = this.arrweek[i].endTime
      obj.prodQty = this.arrweek[i].numweek

      console.log('23232', this.splitdata)
      this.fullscreenLoading = i
      splitSbmit(obj).then((res) => {
        console.log(res)
        if (res.isSuccess) {
          this.chaifentype = 1
          this.chaifentype1 = 1
          this.q_z_formDate = []
          this.query.startTime = ''
          this.query.endTime = ''
          this.fullscreenLoading = -1
          this.arrweek[i].disable = 2
          this.splitTwo(i)
          this.$message.success('拆分成功')
        } else {
          this.fullscreenLoading = -1
          this.$message.error(res.message + ',提交失败')
          return false
        }
      }).catch(() => {
        this.fullscreenLoading = -1
      })

      // this.dialogsplit = false
    },
    continuity() {
      if (this.selectedList.length < 2) {
        this.$message.warning(`请选择多条生产计划进行拆分指令！`)
        return false
      }
      this.selectedList = this.selectedList.toString()
      // if (this.selectedList.charAt(this.selectedList.length-1)==",") {
      //  }else {
      //           this.selectedList=this.selectedList+',';
      //       }
      // console.log(this.selectedList)
      continuityList(this.selectedList).then((res) => {
        this.type = 2
        this.splitdata = res
        this.z_formDate = ''
        this.dialogsplit = true
      })
    },
    getInfo() {
      const a = deepClone(this.query)
      if (!a.startTime) {
        this.$delete(a, 'startTime')
      }
      if (!a.endTime) {
        this.$delete(a, 'endTime')
      }
      this.loading = true
      getInfo(a).then((res) => {
        this.loading = false
        this.tableData = res.data.items
        this.total = res.data.totalItems
      }).catch(() => {
        this.loading = false
      })
    },
    search() {
      this.query.pageIndex = 1
      this.getInfo()
    },
    deleteProductionPlan() {
      if (this.selectedList.length == 0) {
        this.$message.error(`请选择要删除的月计划数据`)
        return false
      }
      console.log(this.checked)

      for (var i = 0; i < this.checked.length; i++) {
        if (this.checked[i].usedNum - 0 !== 0) {
          this.$message.error(`请选择未拆分的月计划进行删除`)
          return false
        }
        // if(this.checked[i].fstatus){
        //   this.$message.warning(`不可删除从ERP获取的月计划`)
        //   return false
        // }
      }
      this.$confirm('确认删除?', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const obj = {
            ids: this.selectedList.toString()
          }
          console.log(obj)
          deleteAll(obj).then((response) => {
            if (response.isSuccess) {
              this.getInfo()
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            } else {
              this.$message({
                type: 'error',
                message: response.message
              })
            }
          })
        })
        .catch((err) => console.error(err))
    },
    // 上传文件个数超过定义的数量
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，请删除后继续上传`)
    },
    // 上传文件
    uploadActionUrl(item) {
      const fileObj = item.file
      // FormData 对象
      const form = new FormData()
      // 文件对象
      form.append('file', fileObj)
      // let formTwo = JSON.stringify(form)
      impProductionPlanData(form).then((response) => {
        if (response.isSuccess) {
          this.getInfo()

          this.$message.info('文件：' + fileObj.name + '上传成功')
          this.$refs.planRef.clearFiles()
        } else {
          this.$message({
            type: 'error',
            message: response.data[0]
          })
        }
      })
    }
  }
}
</script>
